<template>
  <div id="pictureManagePage">
    <a-flex justify="space-between">
      <h2>图片管理</h2>
      <a-space>
        <a-button type="primary" href="/add_picture" target="_blank">+ 创建图片</a-button>
        <a-button type="primary" href="/add_picture/batch" target="_blank" ghost>+ 批量创建图片</a-button>
      </a-space>
    </a-flex>
    <!--    搜索表单-->
    <a-form layout="inline" :model="searchParams" @finish="doSearch">
      <a-form-item label="关键词" name="searchText">
        <a-input
          v-model:value="searchParams.searchText"
          placeholder="从名称和简介搜索"
          allow-clear
        />
      </a-form-item>
      <a-form-item label="类型" name="category">
        <a-input v-model:value="searchParams.category" placeholder="请输入类型" allow-clear />
      </a-form-item>
      <a-form-item label="标签" name="tags">
        <a-select
          v-model:value="searchParams.tags"
          :options="tagOptions"
          mode="tags"
          placeholder="请输入标签"
          style="min-width: 180px"
          allow-clear
        />
      </a-form-item>
      <a-form-item label="审核状态" name="reviewStatus">
        <a-select
          v-model:value="searchParams.reviewStatus"
          :options="PIC_REVIEW_STATUS_OPTIONS"
          placeholder="请输入审核状态"
          style="min-width: 180px"
          allow-clear
        />
      </a-form-item>
      <a-form-item>
        <a-button type="primary" html-type="submit">搜索</a-button>
      </a-form-item>
    </a-form>
    <div style="margin-bottom: 32px" />
    <a-table
      :columns="columns"
      :data-source="dataList"
      :pagination="pagination"
      @change="doTableChange"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex === 'url'">
          <a-image :src="record.url" :width="120" />
        </template>
        <template v-else-if="column.dataIndex === 'tags'">
          <a-space wrap>
            <a-tag v-for="tag in JSON.parse(record.tags || '[]')" :key="tag">{{ tag }}</a-tag>
          </a-space>
        </template>
        <!-- 图片信息 -->
        <template v-if="column.dataIndex === 'picInfo'">
          <div>格式：{{ record.picFormat }}</div>
          <div>宽度：{{ record.picWidth }}</div>
          <div>高度：{{ record.picHeight }}</div>
          <div>宽高比：{{ record.picScale }}</div>
          <div>大小：{{ (record.picSize / 1024).toFixed(2) }}KB</div>
        </template>
        <!-- 审核信息 -->
        <!-- 审核信息 -->
        <template v-if="column.dataIndex === 'reviewMessage'">
          <div>审核状态：{{ PIC_REVIEW_STATUS_MAP[record.reviewStatus] }}</div>
          <div>审核信息：{{ record.reviewMessage }}</div>
          <div>审核人：{{ record.reviewerId }}</div>
        </template>
        <template v-else-if="column.dataIndex === 'createTime'">
          {{ dayjs(record.createTime).format('YYYY-MM-DD HH:mm:ss') }}
        </template>
        <template v-else-if="column.dataIndex === 'editTime'">
          {{ dayjs(record.editTime).format('YYYY-MM-DD HH:mm:ss') }}
        </template>
        <template v-else-if="column.key === 'action'">
          <a-space wrap>
            <a-button
              v-if="record.reviewStatus !== PIC_REVIEW_STATUS_ENUM.PASS"
              type="link"
              @click="handleReview(record.id, PIC_REVIEW_STATUS_ENUM.PASS, '管理员通过审核')"
            >
              通过
            </a-button>
            <a-popconfirm
              v-if="record.reviewStatus !== PIC_REVIEW_STATUS_ENUM.REJECT"
              title="确定拒绝审核吗？"
              ok-text="确定"
              cancel-text="取消"
              @confirm="showModal(record)"
            >
              <a-button type="link" danger> 拒绝</a-button>
              <a-modal v-model:open="open" title="审核未通过" @ok="handleOk">
                <a-form :model="formState">
                  <a-form-item label="拒绝理由">
                    <a-input v-model:value="formState.reason" placeholder="请输入拒绝理由" />
                  </a-form-item>
                </a-form>
              </a-modal>
            </a-popconfirm>
            <a-button type="link" :href="`/add_picture?id=${record.id}`" target="_blank"
            >编辑
            </a-button>
            <!--          点击删除出现弹窗-->
            <a-popconfirm
              title="确定删除吗？"
              ok-text="确定"
              cancel-text="取消"
              @confirm="doDelete(record.id)"
            >
              <a-button danger>删除</a-button>
            </a-popconfirm>
          </a-space>
        </template>
      </template>
    </a-table>
  </div>
</template>
<script lang="ts" setup>
import { computed, onMounted, reactive, ref } from 'vue'
import {
  deletePictureUsingPost,
  doPictureReviewUsingPost,
  listPictureByPageUsingPost,
  listPictureTagCategoryUsingGet
} from '@/api/pictureController.ts'
import { message } from 'ant-design-vue'
import dayjs from 'dayjs'
import {
  PIC_REVIEW_STATUS_ENUM,
  PIC_REVIEW_STATUS_MAP,
  PIC_REVIEW_STATUS_OPTIONS
} from '@/constants/picture.ts'

const columns = [
  {
    title: 'id',
    dataIndex: 'id',
    width: 80
  },
  {
    title: '图片',
    dataIndex: 'url'
  },
  {
    title: '名称',
    dataIndex: 'name'
  },
  {
    title: '简介',
    dataIndex: 'introduction',
    ellipsis: true
  },
  {
    title: '类型',
    dataIndex: 'category'
  },
  {
    title: '标签',
    dataIndex: 'tags'
  },
  {
    title: '图片信息',
    dataIndex: 'picInfo'
  },
  {
    title: '用户 id',
    dataIndex: 'userId',
    width: 80
  },
  {
    title: '审核信息',
    dataIndex: 'reviewMessage'
  },
  {
    title: '创建时间',
    dataIndex: 'createTime'
  },
  {
    title: '编辑时间',
    dataIndex: 'editTime'
  },
  {
    title: '操作',
    key: 'action'
  }
]

const dataList = ref<API.Picture[]>([])
const total = ref<number>(0)

// 搜索条件
const searchParams = reactive<API.PictureQueryRequest>({
  current: 1,
  pageSize: 5,
  sortField: 'createTime',
  sortOrder: 'descend'
})
// 分页
const pagination = computed(() => ({
  total: total.value,
  current: searchParams.current,
  pageSize: searchParams.pageSize,
  showSizeChanger: true,
  showTotal: (total: never) => `共${total}条数据`
}))
const doSearch = () => {
  searchParams.current = 1
  getTableData()
}

interface pagination {
  current: number,
  pageSize: number,
}

// 表格变化数据
const doTableChange = (pagination: pagination) => {
  searchParams.current = pagination.current
  searchParams.pageSize = pagination.pageSize
  getTableData()
}
// 获取表格数据
const getTableData = async () => {
  const res = await listPictureByPageUsingPost({
    ...searchParams,
    nullSpaceId: true
  })
  if (res.data.code === 0 && res.data.data) {
    dataList.value = res.data.data.records ?? []
    total.value = Number(res.data.data.total ?? 0)
  } else {
    message.error('获取图片列表失败,' + res.data.message)
  }
}
onMounted(() => {
  getTableData()
  getTagList()
})
// 删除图片
const doDelete = async (id: number) => {
  const res = await deletePictureUsingPost({ id })
  if (res.data.code === 0 && res.data.data) {
    message.success('删除成功')
    await getTableData()
  } else {
    message.error('删除失败,' + res.data.message)
  }
}
// 获取标签
const tagOptions = ref<{ label: string; value: string }[]>([])
const getTagList = async () => {
  const res = await listPictureTagCategoryUsingGet()
  if (res.data.code === 0 && res.data.data) {
    // 转换成下拉选项组件接受的格式
    tagOptions.value = (res.data.data.tagList ?? []).map((data: string) => {
      return {
        value: data,
        label: data
      }
    })
  } else {
    message.error('加载分类标签失败，' + res.data.message)
  }
}
// 审核图片
const open = ref<boolean>(false)
const currentRecord = ref<API.Picture>()
const formState = reactive({
  reason: ''
})
const showModal = (record: API.Picture) => {
  currentRecord.value = record
  open.value = true
}
const handleReview = async (id: number, reviewStatus: number, reviewMessage: string) => {
  // reviewMessage = reviewStatus === PIC_REVIEW_STATUS_ENUM.PASS ? '管理员通过审核' : '管理员拒绝审核'
  const res = await doPictureReviewUsingPost({
    id: id,
    reviewStatus,
    reviewMessage
  })
  if (res.data.code === 0 && res.data.data) {
    message.success('审核成功')
    await getTableData()
  } else {
    message.error('审核失败，' + res.data.message)
  }
}
const handleOk = () => {
  if (!formState.reason) {
    formState.reason = '管理员拒绝审核'
  }
  handleReview(currentRecord?.value?.id ?? 0, PIC_REVIEW_STATUS_ENUM.REJECT, formState.reason)
  open.value = false
}
</script>
